﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player_Controller : MonoBehaviour {

    private Vector3 touchPosition;
    private bool canMove;
    public float coefDiminish;

    [Header("Min & Max Pos")]
    public Transform MinPlatformPos;
    public Transform MaxPlatformPos;
    public float offset;

    [Header("Sounds Management")]
    public AudioSource Squeaky;

    [Header(" Shrinking Management ")]
    public float shrinkingCoef;
    float shrinkDelay = 5;
    float shrinkTime = 0;

    [Header("Particles")]
    public ParticleSystem HitParticles;

    // Use this for initialization
    void Start()
    {
        canMove = false;
    }

    // Update is called once per frame
    void Update()
    {

        if (Game_Controller.gameOn)
        {

            //Shrink
            Shrink();

            if (Input.GetMouseButtonDown(0) && !canMove)
            {
                touchPosition = Input.mousePosition;
                canMove = true;
            }
            else if (Input.GetMouseButtonUp(0))
            {
                canMove = false;
            }

            if (canMove)
                MovePlatform();
        }

    }

    void Shrink(){

        if(shrinkTime < shrinkDelay){
            shrinkTime += Time.deltaTime;
        }
        else 
        {
			transform.localScale -= new Vector3(coefDiminish, 0, 0);

			shrinkTime = 0;

        }
    }

    void MovePlatform()
    {
        //Store the distance
        float diff = touchPosition.x - Input.mousePosition.x;
        diff *= -coefDiminish;

        if (transform.position.x <= MaxPlatformPos.position.x &&
            transform.position.x >= MinPlatformPos.position.x)
        {
            //Move the Platform
            Vector3 pos = transform.position;
            pos.x += diff;
            transform.position = pos;

            //Reset the pos
            touchPosition = Input.mousePosition;

        }
        else if (transform.position.x > MaxPlatformPos.position.x)
            transform.position = MaxPlatformPos.position;// - new Vector3(offset,0,0);
        else if (transform.position.x < MinPlatformPos.position.x)
            transform.position = MinPlatformPos.position;// + new Vector3(offset, 0, 0);

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.transform.tag == "Ball")
        {
            //Add a point
            Game_Controller.SCORE++;

            collision.transform.GetComponent<Rigidbody2D>().AddForce(new Vector2(5, 0));

            //Play the Particles
            Vector2 pos = collision.contacts[0].point;
            HitParticles.transform.position = pos;
            HitParticles.Play();

            //Play the squeaky sound
            PlaySqueakySound();
        }
    }


    public void PlaySqueakySound(){

        Squeaky.Play();

    }
}
